package com.ilink.teacherservice.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.ilink.ilinkapi.dto.teacher.UpdateJsonStatusRequest;
import com.ilink.ilinkcommon.log.method.MethodLog;
import com.ilink.teacherservice.entity.DTO.UploadJsonRequest;
import com.ilink.teacherservice.entity.PO.study.tree.JsonEntity;
import com.ilink.teacherservice.entity.PO.study.tree.JsonTagEntity;
import com.ilink.teacherservice.entity.PO.study.tree.StudyTreeFavorite;
import com.ilink.teacherservice.entity.PO.study.tree.TagEntity;
import com.ilink.ilinkcommon.domain.R;
import com.ilink.ilinkcommon.service.oss.OssService;
import com.ilink.teacherservice.service.StudyTreeFavoriteService;
import com.ilink.teacherservice.service.StudyTreeJsonService;
import com.ilink.ilinkcommon.utils.UserContext;
import java.util.ArrayList;
import java.util.List;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.json.JSONObject;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * <h3>new-ilink-java-backend</h3>
 *
 * @Description <p>学习广场——技能树</p>
 * @Author 郑千鹤
 * @Date 2024-09-15 19:48
 **/
@Slf4j
@Component
@RequiredArgsConstructor
@RestController
@RequestMapping("/teacher/study_tree_json")
public class StudyTreeJsonController {

    private final StudyTreeJsonService studyTreeJsonService;
    private final StudyTreeFavoriteService studyTreeFavoriteService;
    private final OssService ossService;

    /**
     * @author dzy
     * @return 最常使用的8个标签(List<TagEntity>形式)
     */
    @MethodLog("获取最常使用的技能树标签")
    @GetMapping("/getCommonStudyTreeTags")
    public R getCommonStudyTreeTags(){
        try {
            return R.ok(studyTreeJsonService.getCommonTags());
        } catch(Exception e){
            return R.error ("内部服务器错误：" + e);
        }
    }

    /**
     * @Author 郑千鹤 获取全部标签
     * @Description
     * @Date 19:54 2024/9/15
     * @Param []
     * @return com.ilink.ilinkcommon.domain.R
     **/
    @MethodLog("获取全部标签")
    @GetMapping("/tags")
    public R getAllTags() {
        try {
            return R.ok(studyTreeJsonService.getAllTags());
        } catch (Exception e) {
            return R.error("获取标签时发生错误：" + e.getMessage());
        }
    }
    /**
     * @Author 郑千鹤
     * @Description //根据标签、关键词、分页大小查找
     * @Date 19:56 2024/9/15
     * @Param [tags, keyword, page, size]
     * @return com.ilink.ilinkcommon.domain.R
     **/
    @MethodLog("根据标签、关键词、分页大小查找")
    @GetMapping
    public R getJsonsByTagsAndPagination(
        @RequestParam List<String> tags,
        @RequestParam String keyword,
        @RequestParam int page,
        @RequestParam int size) {
        try {
            return R.ok(studyTreeJsonService.getJsonsByTagsAndPagination(tags, keyword, page, size));
        } catch (Exception e) {
            return R.error("根据标签和分页获取Json时发生错误：" + e.getMessage());
        }
    }
    /**
     * @Author 郑千鹤
     * @Description //根据id查询技能树详情
     * @Date 19:57 2024/9/15
     * @Param [id]
     * @return com.ilink.ilinkcommon.domain.R
     **/
    @MethodLog("根据id查询技能树详情")
    @GetMapping("/detail")
    public R getJsonById(@RequestParam Long id) {
        try {
            return R.ok(studyTreeJsonService.getJsonById(id));
        } catch (Exception e) {
            return R.error("获取Json详情时发生错误：" + e.getMessage());
        }
    }
    /**
     * @Author 郑千鹤
     * @Description //获取资源图片url
     * @Date 19:57 2024/9/15
     * @Param [filename]
     * @return com.ilink.ilinkcommon.domain.R
     **/
    @MethodLog("获取资源图片url")
    @GetMapping("/getUrl")
    public R getUrl(@RequestParam String filename) {
        try {
            return R.ok(null, ossService.getStudyTreeResourceUrl("dataset-square-migrate", "json_resource/" + filename));
        } catch (Exception e) {
            return R.error("获取资源图片URL时发生错误：" + e.getMessage());
        }
    }


    /*
    编写人：张博
    用途：技能树用户个人收藏
     */
    @MethodLog("技能树用户个人收藏")
    @PostMapping("/add_favorite_tree")
    public R addFavoriteTree(@RequestBody String jsonString) {
        try {
            JSONObject jsonObject = new JSONObject(jsonString);
            String treeId = jsonObject.getString("treeId");
            String userId = UserContext.getUserId();
            String result = studyTreeFavoriteService.insertFavoriteTree(userId, Long.valueOf(treeId));
            if ("收藏成功".equals(result)) {
                return R.ok(result);
            }
            return R.error(result); // 返回具体的错误信息
        } catch (Exception e) {
            return R.error("收藏操作失败，错误信息：" + e.getMessage());
        }
    }

    /**
     * @Author zhengqianhe
     * @Description //取消收藏，限一次
     * @Date 15:26 2024/9/18
     * @Param [jsonString]
     * @return com.ilink.ilinkcommon.domain.R
     **/
    @MethodLog("取消收藏")
    @PostMapping("/remove_favorite_tree")
    public R removeFavoriteTree(@RequestBody String jsonString) {
        try {
            JSONObject jsonObject = new JSONObject(jsonString);
            String treeId = jsonObject.getString("treeId");
            String userId = UserContext.getUserId();
            String result = studyTreeFavoriteService.removeFavoriteTree(userId, treeId);

            if ("取消收藏成功".equals(result)) {
                return R.ok(result);
            } else {
                return R.error(result); // 返回具体的错误信息
            }
        } catch (Exception e) {
            log.error(e.getMessage());
            return R.error("取消收藏操作失败，错误信息：" + e.getMessage());
        }
    }


    /*
    编写人：张博
    用途：返回指定用户的收藏列表
     */
    // 获取指定用户的收藏列表
    @MethodLog("获取指定用户的收藏列表")
    @GetMapping("/list_favorite")
    public R getFavoriteList() {
        try{
            String userId = UserContext.getUserId();
            List<StudyTreeFavorite> favoriteList = studyTreeFavoriteService.getFavoriteListByUserId(userId);
            if(favoriteList != null){
                return R.ok("用户的列表",favoriteList);
            }
            return R.error("用户未收藏技能树");
        }catch (Exception e){
            return R.error("获取用户的收藏列表错误"+e.getMessage());
        }
    }

    /**
     * @Author 郑千鹤
     * @Description //更新技能树状态
     * @Date 19:58 2024/9/15
     * @Param [updateJsonStatusRequest]
     * @return com.ilink.ilinkcommon.domain.R
     **/
    @MethodLog("更新技能树状态")
    @PostMapping("/update_status")
    public R updateJsonStatus(@RequestBody UpdateJsonStatusRequest updateJsonStatusRequest) {
        try {
            studyTreeJsonService.updateJsonStatus(updateJsonStatusRequest);
            return R.ok("技能树状态更新成功");
        } catch (Exception e) {
            return R.error("更新技能树状态时发生错误：" + e.getMessage());
        }
    }

    /**
     * 下面两个接口用于后端上传文件，前端无需请求
     */
    @MethodLog
    @PostMapping("/upload")
    public R uploadJson(@RequestBody UploadJsonRequest request) {
        ObjectMapper objectMapper = new ObjectMapper();

        // Step 1: Create a new JsonEntity and set its fields
        JsonEntity jsonEntity = new JsonEntity();
        jsonEntity.setName(request.getName());
        jsonEntity.setDescription(request.getIntroduction());
        jsonEntity.setImageUrl(request.getProjectImage());

        try {
            String jsonContent = objectMapper.writeValueAsString(request.getContent());
            jsonEntity.setJsonContent(jsonContent);
        } catch (Exception e) {
            return R.error("Invalid JSON content format");
        }

        // Step 2: Save the JsonEntity
        studyTreeJsonService.saveJsonEntity(jsonEntity);

        // Step 3: Process tags and save them in the database
        List<Long> tagIds = new ArrayList<>();
        if (request.getTaps() != null) {
            for (String tagName : request.getTaps()) {
                TagEntity tagEntity = studyTreeJsonService.getOrCreateTag(tagName);
                tagIds.add(tagEntity.getTagId());
            }

            // Step 4: Save JsonTagEntity for each tag
            for (Long tagId : tagIds) {
                JsonTagEntity jsonTagEntity = new JsonTagEntity();
                jsonTagEntity.setJsonId(jsonEntity.getId());
                jsonTagEntity.setTagId(tagId);
                studyTreeJsonService.saveJsonTagEntity(jsonTagEntity);
            }
        } else {
            return R.error("Tags (Taps) cannot be null or empty");
        }

        return R.ok("JSON uploaded successfully");
    }

    @MethodLog
    @GetMapping("/insert_status")
    public R testInsert(){
        studyTreeJsonService.storeJsonCopiesForUser("ca96b2942b14380264");
        return R.ok("创建成功");
    }

}